<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Wallet, Promotion, Present } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const activeTab = ref(authStore.isPartner ? 'chat' : 'live') // 合作伙伴默认显示聊天室标签页
const sending = ref(false)
const loading = ref(false)
const loadingRecords = ref(false)
const currentBalance = ref(0)
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

// 表单数据
const liveForm = ref({
  roomId: null,
  giftId: null,
  quantity: 1
})

const chatForm = ref({
  roomId: null,
  giftId: null,
  quantity: 1,
  receiverUserId: null
})

// 计算属性
const isAdmin = computed(() => authStore.isAdmin)

// 数据列表
const liveRooms = ref<any[]>([])
const chatRooms = ref<any[]>([])
const gifts = ref<any[]>([])
const records = ref<any[]>([])
const chatRoomUsers = ref<any[]>([])

// 获取直播间列表
async function fetchLiveRooms() {
  try {
    const { data } = await request.get('/api/admin/live-rooms?limit=100')
    liveRooms.value = data.liveRooms || []
  } catch (error) {
    console.error('获取直播间列表失败:', error)
  }
}

// 获取聊天室列表
async function fetchChatRooms() {
  try {
    const { data } = await request.get('/api/admin/chat-rooms?limit=100')
    chatRooms.value = data.rooms || []
  } catch (error) {
    console.error('获取聊天室列表失败:', error)
  }
}

// 获取礼物列表
async function fetchGifts() {
  try {
    const { data } = await request.get('/api/admin/gifts')
    gifts.value = (data || []).filter((g: any) => g.isActive)
  } catch (error) {
    console.error('获取礼物列表失败:', error)
  }
}

// 获取当前用户积分余额
async function fetchCurrentBalance() {
  if (isAdmin.value) return // 管理员不需要显示积分余额

  try {
    const { data } = await request.get('/api/auth/me')
    if (data?.wallet?.pointsBalance) {
      currentBalance.value = Number(data.wallet.pointsBalance)
    }
  } catch (error) {
    console.error('获取积分余额失败:', error)
  }
}

// 获取聊天室用户列表
async function fetchChatRoomUsers(roomId: any) {
  if (!roomId) {
    chatRoomUsers.value = []
    return
  }

  try {
    const response = await request.get(`/api/chat/rooms/${roomId}/users?limit=100&windowSec=3600`)
    chatRoomUsers.value = response.data?.users || []
  } catch (error) {
    console.error('获取聊天室用户失败:', error)
    chatRoomUsers.value = []
  }
}

// 发送直播间礼物
async function sendLiveGift() {
  if (!liveForm.value.roomId || !liveForm.value.giftId) {
    ElMessage.warning('请选择直播间和礼物')
    return
  }

  // 合作伙伴需要检查积分余额
  if (!isAdmin.value) {
    const gift = gifts.value.find(g => g.id === liveForm.value.giftId)
    if (gift) {
      const totalCost = gift.pricePoints * liveForm.value.quantity
      if (currentBalance.value < totalCost) {
        ElMessage.error(`적분이 부족합니다! 필요: ${formatPoints(totalCost)} 적분, 현재 잔액: ${formatPoints(currentBalance.value)}`)
        return
      }
    }
  }

  sending.value = true
  try {
    await request.post(`/api/live/rooms/${liveForm.value.roomId}/gifts/send`, {
      giftId: liveForm.value.giftId,
      quantity: liveForm.value.quantity
    })
    ElMessage.success('선물 발송 성공')
    // 重置表单
    liveForm.value = { roomId: null, giftId: null, quantity: 1 }
    // 刷新积分余额和记录
    if (!isAdmin.value) {
      await fetchCurrentBalance()
    }
    fetchRecords()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '발송 실패')
  } finally {
    sending.value = false
  }
}

// 发送聊天室礼物（1对1发送给指定用户）
async function sendChatGift() {
  if (!chatForm.value.roomId || !chatForm.value.giftId || !chatForm.value.receiverUserId) {
    ElMessage.warning('채팅방, 선물, 수신자를 모두 선택하세요')
    return
  }

  // 合作伙伴需要检查积分余额
  if (!isAdmin.value) {
    const gift = gifts.value.find(g => g.id === chatForm.value.giftId)
    if (gift) {
      const totalCost = gift.pricePoints * chatForm.value.quantity
      if (currentBalance.value < totalCost) {
        ElMessage.error(`적분이 부족합니다! 필요: ${formatPoints(totalCost)} 적분, 현재 잔액: ${formatPoints(currentBalance.value)}`)
        return
      }
    }
  }

  sending.value = true
  try {
    await request.post(`/api/chat/rooms/${chatForm.value.roomId}/gifts/send`, {
      giftId: chatForm.value.giftId,
      quantity: chatForm.value.quantity,
      receiverUserId: chatForm.value.receiverUserId
    })
    ElMessage.success('선물 발송 성공')
    // 重置表单
    resetChatForm()
    // 刷新积分余额和记录
    if (!isAdmin.value) {
      await fetchCurrentBalance()
    }
    fetchRecords()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '발송 실패')
  } finally {
    sending.value = false
  }
}

// 获取发送记录
async function fetchRecords() {
  loadingRecords.value = true
  try {
    const { data } = await request.get('/api/admin/admin-gift-sends?limit=20')
    records.value = data || []
  } catch (error) {
    console.error('获取记录失败:', error)
    ElMessage.error('발송 기록 가져오기 실패')
  } finally {
    loadingRecords.value = false
  }
}

// 重置表单
function resetLiveForm() {
  liveForm.value = { roomId: null, giftId: null, quantity: 1 }
}

function resetChatForm() {
  chatForm.value = { roomId: null, giftId: null, quantity: 1, receiverUserId: null }
  chatRoomUsers.value = []
}

// 刷新所有数据
async function fetchData() {
  loading.value = true
  try {
    const promises = [
      fetchChatRooms(),
      fetchGifts(),
      fetchRecords()
    ]

    // 管理员需要获取直播间列表
    if (isAdmin.value) {
      promises.push(fetchLiveRooms())
    }

    // 合作伙伴需要获取积分余额
    if (!isAdmin.value) {
      promises.push(fetchCurrentBalance())
    }

    await Promise.all(promises)
    ElMessage.success('데이터 새로고침 완료')
  } catch {
    ElMessage.error('데이터 새로고침 실패')
  } finally {
    loading.value = false
  }
}

// 监听聊天室变化，自动获取用户列表
watch(() => chatForm.value.roomId, (newRoomId) => {
  if (newRoomId) {
    fetchChatRoomUsers(newRoomId)
  } else {
    chatRoomUsers.value = []
  }
  // 重置收礼人选择
  chatForm.value.receiverUserId = null
})

// 工具函数
function formatPoints(points: number | string): string {
  return Number(points || 0).toLocaleString()
}

function getImageUrl(url: string) {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `${API_BASE_URL}${url}`
}

onMounted(async () => {
  await fetchData()
})
</script>

<template>
  <div class="gift-send-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <Promotion />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">선물 발송</h1>
          <p class="page-subtitle">사용자에게 선물을 발송합니다</p>
        </div>
      </div>
    </div>

    <!-- 积分余额显示（仅合作伙伴） -->
    <div v-if="!isAdmin" class="balance-section">
      <div class="balance-card">
        <el-icon class="balance-icon"><Wallet /></el-icon>
        <div class="balance-info">
          <div class="balance-label">현재 포인트 잔액</div>
          <div class="balance-value">{{ formatPoints(currentBalance) }}</div>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button :icon="Refresh" @click="fetchData" :loading="loading" size="small">
        데이터 새로고침
      </el-button>
    </div>

    <!-- 标签页 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab" class="mobile-tabs">
        <!-- 관리자는 라이브 방 선물을 보낼 수 있습니다 -->
        <el-tab-pane v-if="isAdmin" label="라이브 방 선물" name="live">
          <div class="tab-content">
            <div class="send-form-card">
              <div class="form-header">
                <el-icon><Present /></el-icon>
                <span>라이브 방 선물 발송</span>
              </div>

              <el-form :model="liveForm" label-position="top" class="mobile-form">
                <el-form-item label="라이브 방 선택" required>
                  <el-select v-model="liveForm.roomId" placeholder="라이브 방을 선택하세요" class="full-width">
                    <el-option
                      v-for="room in liveRooms"
                      :key="room.id"
                      :label="room.title || room.channel?.name || `라이브 방${room.id}`"
                      :value="room.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="선물 선택" required>
                  <el-select v-model="liveForm.giftId" placeholder="선물을 선택하세요" class="full-width">
                    <el-option
                      v-for="gift in gifts"
                      :key="gift.id"
                      :label="`${gift.name} (${formatPoints(gift.pricePoints)}포인트)`"
                      :value="gift.id"
                    >
                      <div class="gift-option">
                        <img
                          v-if="gift.iconUrl"
                          :src="getImageUrl(gift.iconUrl)"
                          :alt="gift.name"
                          class="gift-option-icon"
                        />
                        <div class="gift-option-icon-placeholder" v-else>🎁</div>
                        <div class="gift-option-info">
                          <div class="gift-option-name">{{ gift.name }}</div>
                          <div class="gift-option-price">{{ formatPoints(gift.pricePoints) }}포인트</div>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="수량">
                  <el-input-number
                    v-model="liveForm.quantity"
                    :min="1"
                    :max="99"
                    class="full-width"
                    controls-position="right"
                  />
                </el-form-item>

                <el-form-item>
                  <div class="form-actions">
                    <el-button @click="resetLiveForm">초기화</el-button>
                    <el-button type="primary" @click="sendLiveGift" :loading="sending">
                      선물 발송
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="채팅방 선물" name="chat">
          <div class="tab-content">
            <div class="send-form-card">
              <div class="form-header">
                <el-icon><Present /></el-icon>
                <span>채팅방 선물 발송</span>
              </div>

              <el-form :model="chatForm" label-position="top" class="mobile-form">
                <el-form-item label="채팅방 선택" required>
                  <el-select
                    v-model="chatForm.roomId"
                    placeholder="채팅방을 선택하세요"
                    class="full-width"
                    @change="fetchChatRoomUsers"
                  >
                    <el-option
                      v-for="room in chatRooms"
                      :key="room.id"
                      :label="room.title || `채팅방${room.id}`"
                      :value="room.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="수신자 선택" required>
                  <el-select
                    v-model="chatForm.receiverUserId"
                    placeholder="먼저 채팅방을 선택하세요"
                    class="full-width"
                    :disabled="!chatForm.roomId || chatRoomUsers.length === 0"
                  >
                    <el-option
                      v-for="user in chatRoomUsers"
                      :key="user.id"
                      :label="user.nickname || user.name || `사용자${user.id}`"
                      :value="user.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="선물 선택" required>
                  <el-select v-model="chatForm.giftId" placeholder="선물을 선택하세요" class="full-width">
                    <el-option
                      v-for="gift in gifts"
                      :key="gift.id"
                      :label="`${gift.name} (${formatPoints(gift.pricePoints)}포인트)`"
                      :value="gift.id"
                    >
                      <div class="gift-option">
                        <img
                          v-if="gift.iconUrl"
                          :src="getImageUrl(gift.iconUrl)"
                          :alt="gift.name"
                          class="gift-option-icon"
                        />
                        <div class="gift-option-icon-placeholder" v-else>🎁</div>
                        <div class="gift-option-info">
                          <div class="gift-option-name">{{ gift.name }}</div>
                          <div class="gift-option-price">{{ formatPoints(gift.pricePoints) }}포인트</div>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="수량">
                  <el-input-number
                    v-model="chatForm.quantity"
                    :min="1"
                    :max="99"
                    class="full-width"
                    controls-position="right"
                  />
                </el-form-item>

                <el-form-item>
                  <div class="form-actions">
                    <el-button @click="resetChatForm">초기화</el-button>
                    <el-button type="primary" @click="sendChatGift" :loading="sending">
                      선물 발송
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 최근 발송 기록 -->
    <div class="records-section">
      <div class="records-card">
        <div class="card-header">
          <div class="header-title">
            <el-icon><Present /></el-icon>
            <span>최근 발송 기록</span>
          </div>
          <el-button @click="fetchRecords" :loading="loadingRecords" size="small" :icon="Refresh">
            새로고침
          </el-button>
        </div>

        <div v-loading="loadingRecords" class="records-content">
          <div v-if="records.length === 0" class="empty-state">
            <el-empty description="발송 기록이 없습니다" />
          </div>
          <div v-else class="records-list">
            <div v-for="record in records" :key="record.id" class="record-item">
              <div class="record-header">
                <div class="record-header-left">
                  <el-tag :type="record.type === 'live' ? 'primary' : 'success'" size="small">
                    {{ record.type === 'live' ? '라이브 방' : '채팅방' }}
                  </el-tag>
                  <img
                    v-if="record.giftIcon"
                    :src="getImageUrl(record.giftIcon)"
                    :alt="record.giftName"
                    class="record-gift-icon"
                  />
                  <span v-else class="record-gift-placeholder">🎁</span>
                </div>
                <span class="record-time">{{ new Date(record.createdAt).toLocaleString() }}</span>
              </div>
              <div class="record-content">
                <div class="record-row">
                  <span class="label">방:</span>
                  <span class="value">{{ record.roomName }}</span>
                </div>
                <div class="record-row">
                  <span class="label">선물:</span>
                  <span class="value">{{ record.giftName }}</span>
                </div>
                <div class="record-row">
                  <span class="label">수량:</span>
                  <span class="value">{{ record.quantity }}개</span>
                </div>
                <div class="record-row">
                  <span class="label">포인트:</span>
                  <span class="value points">{{ formatPoints(record.totalPoints) }}</span>
                </div>
                <div v-if="record.receiverName" class="record-row">
                  <span class="label">수신자:</span>
                  <span class="value">{{ record.receiverName }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.gift-send-management {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: #f5f5f5;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-icon {
  color: var(--el-color-primary);
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

/* 积分余额区域 */
.balance-section {
  margin-bottom: 16px;
}

.balance-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border-radius: 8px;
  color: white;
}

.balance-icon {
  font-size: 24px;
}

.balance-info {
  flex: 1;
}

.balance-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 4px;
}

.balance-value {
  font-size: 20px;
  font-weight: 600;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

/* 标签页容器 */
.tabs-container {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: visible;
  margin-bottom: 16px;
  min-height: 400px;
}

.mobile-tabs {
  height: 100%;
}

.mobile-tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 16px;
  background: #fafafa;
  border-bottom: 1px solid var(--el-border-color-light);
}

.mobile-tabs :deep(.el-tabs__nav-wrap) {
  padding: 8px 0;
}

.mobile-tabs :deep(.el-tabs__item) {
  font-size: 14px;
  padding: 0 12px;
  height: 36px;
  line-height: 36px;
}

.mobile-tabs :deep(.el-tabs__content) {
  padding: 0;
  height: auto;
  min-height: 350px;
}

/* 标签页内容 */
.tab-content {
  padding: 16px;
}

/* 发送表单卡片 */
.send-form-card {
  background: white;
  border-radius: 8px;
  overflow: visible;
  border: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

.form-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid var(--el-border-color-lighter);
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.mobile-form {
  padding: 16px;
  min-height: 200px;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form :deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.full-width {
  width: 100%;
}

.full-width :deep(.el-input__wrapper) {
  width: 100%;
}

.full-width :deep(.el-select) {
  width: 100%;
}

.form-actions {
  display: flex;
  gap: 12px;
}

.form-actions .el-button {
  flex: 1;
}

/* 礼物选择样式 */
.gift-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 4px;
  width: 100%;
}

.gift-option-icon {
  width: 32px;
  height: 32px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
  flex-shrink: 0;
}

.gift-option-icon-placeholder {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  font-size: 16px;
  flex-shrink: 0;
}

.gift-option-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.gift-option-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.gift-option-price {
  font-size: 12px;
  color: var(--el-color-warning);
  font-weight: 500;
}

/* 记录区域 */
.records-section {
  flex-shrink: 0;
  max-height: 400px;
}

.records-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.records-content {
  max-height: 300px;
  overflow-y: auto;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.records-list {
  padding: 16px;
}

.record-item {
  padding: 12px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  margin-bottom: 12px;
}

.record-item:last-child {
  margin-bottom: 0;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-gift-icon {
  width: 20px;
  height: 20px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
}

.record-gift-placeholder {
  font-size: 16px;
}

.record-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.record-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.record-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-row .label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  min-width: 60px;
}

.record-row .value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  text-align: right;
  flex: 1;
}

.record-row .value.points {
  font-weight: 600;
  color: var(--el-color-warning);
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select-dropdown) {
  max-height: 300px;
}

:deep(.el-select-dropdown__item) {
  padding: 0;
  height: auto;
  line-height: normal;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

/* 响应式适配 */
@media (max-width: 480px) {
  .gift-send-management {
    padding: 12px;
  }

  .header-content {
    padding: 12px;
  }

  .page-title {
    font-size: 16px;
  }

  .balance-card {
    padding: 12px;
  }

  .balance-value {
    font-size: 18px;
  }

  .tab-content {
    padding: 12px;
  }

  .mobile-form {
    padding: 12px;
  }

  .records-list {
    padding: 12px;
  }

  .gift-option-icon,
  .gift-option-icon-placeholder {
    width: 28px;
    height: 28px;
  }

  .gift-option-icon-placeholder {
    font-size: 14px;
  }
}
</style>
